﻿using System.Text.Json;

namespace P4_BbookStore;

public class BookManager
{
    private const string FilePath="books.json";
    public List<Book> Books { get; set; } = new List<Book>();
    //构造函数 
    public BookManager()
    {
        LoadFromFile();
    }

    //从文件中加载
    public void LoadFromFile()
    {
        
        if (File.Exists(FilePath))
        {
            string json = File.ReadAllText(FilePath);
            Books = JsonSerializer.Deserialize<List<Book>>(json) ?? new List<Book>(); 
        }
    }
    
    //保存到文件
    public void SaveToFile()
    {
        string json = JsonSerializer.Serialize(Books);
        File.WriteAllText(FilePath, json);
    }
    
    //增加图书
    public void AddBook(string title, string author, int stock)
    {
        Books.Add(new Book(title, author, stock));
        SaveToFile();
    }
    public void AddBook(Book book)
    {
        Books.Add(book);
    }
    //删除图书
    public void DeleteBook(string title)
    {
        var book = Books.FirstOrDefault(b => b.Title == title);
        if (book != null)
        {
            Books.Remove(book);
            SaveToFile();
            Console.WriteLine($"Deleted book {title}");
        }
        else
        {
            Console.WriteLine("Book not found");
        }
        
    }
    public void DeleteBook(Book book)
    {
        Books.Remove(book);
        SaveToFile();
        Console.WriteLine($"Deleted book {book.Title}");
    }
    //列出图书
    public void Print()
    {
        Books.ForEach(book => Console.WriteLine(book.Title));
    }
    //查找图书
    public void FindBook(string title)
    {
        var book = Books.FirstOrDefault(b => b.Title == title);
        if (book != null)
        {
            Console.WriteLine($"Found book {title}, stock: {book.Stock} ");
        }
        else
        {
            Console.WriteLine("Book not found");
        }
    }
    //修改图书
    public void ModifyBook(string title, int stock)
    {
        var book = Books.FirstOrDefault(b => b.Title == title);
        if (book != null)
        {
            book.Stock = stock;
            SaveToFile();
            Console.WriteLine($"Modified book,stock: {book.Stock} ");
        }
        else
        {
            Console.WriteLine("Book not found");
        }
    }
    
}